package com.ws.universal.tools.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;

import com.ws.universal.tools.ContextInit;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Locale;

public class LocationUtils {
    static LocationUtils locationUtils;
    private LocationManager locationManager;
    private String locationProvider;
    private Location myLlocation;

    public static LocationUtils getInstance() {
        if (locationUtils == null) {
            locationUtils = new LocationUtils();
        }
        return locationUtils;
    }

    public String getAddress(Context context) {
        if (!isOPenGPS(context)) {
            ToastUtils.showShort("未开启定位，无法获取地理位置");
            return "";
        }
        String strLocation = "";
        DecimalFormat df = new DecimalFormat("#####0.0000");
        if (!checkPermission(context, permission.ACCESS_COARSE_LOCATION)) {

            ToastUtils.showShort("定位权限关闭，无法获取地理位置");
        }
        try {
            //获取系统的服务，
            locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
            //创建一个criteria对象
            Criteria criteria = new Criteria();
            criteria.setAccuracy(Criteria.ACCURACY_COARSE);
            //设置不需要获取海拔方向数据
            criteria.setAltitudeRequired(false);
            criteria.setBearingRequired(false);
            //设置允许产生资费
            criteria.setCostAllowed(true);
            //要求低耗电
            criteria.setPowerRequirement(Criteria.POWER_LOW);
            String provider = locationManager.getBestProvider(criteria, true);
            LogcatUtils.e("LocationTool", "Location Provider is " + provider);
            @SuppressLint("MissingPermission") Location location = locationManager.getLastKnownLocation(provider);

            //第一次获得设备的位置
            if (location != null) {
//                strLocation = df.format(location.getLatitude()) + "," + df.format(location.getLongitude());
                // 耗时操作
                strLocation += "" + getLocationAddress(context, location);
                if (strLocation.equals("")) {
                    strLocation += "" + getLocationAddress(context, location.getLatitude(), location.getLongitude());
                }
            }


        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return strLocation;

    }

    @SuppressLint("MissingPermission")
    public Location getLocation() {
        //1.获取位置管理器
        locationManager = (LocationManager) ContextInit.getContext().getSystemService(Context.LOCATION_SERVICE);
        //2.获取位置提供器，GPS或是NetWork
        List<String> providers = locationManager.getProviders(true);
        if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
            //如果是网络定位
            locationProvider = LocationManager.NETWORK_PROVIDER;
        } else if (providers.contains(LocationManager.GPS_PROVIDER)) {
            //如果是GPS定位
            locationProvider = LocationManager.GPS_PROVIDER;
        } else if (providers.contains(LocationManager.PASSIVE_PROVIDER)) {
            //如果是PASSIVE定位
            locationProvider = LocationManager.PASSIVE_PROVIDER;
        } else {
            LogcatUtils.e("没有可用的位置提供器：");
            return myLlocation;
        }
        myLlocation = locationManager.getLastKnownLocation(locationProvider);
        if (myLlocation != null) {
            LogcatUtils.e("经纬度信息：if " + myLlocation.getLongitude() + "  " + myLlocation.getLatitude());
            return myLlocation;
        } else {
            // 监视地理位置变化，第二个和第三个参数分别为更新的最短时间minTime和最短距离minDistace
            locationManager.requestLocationUpdates(locationProvider, 3, 3, new LocationListener() {
                // 如果位置发生变化，重新显示
                @Override
                public void onLocationChanged(Location location) {

                    LogcatUtils.e("经纬度信息：else ", location.getLongitude() + "  " + location.getLatitude());
                    myLlocation = location;

                }
            });
            return myLlocation;
        }
    }


    private boolean checkPermission(Context context, permission permName) {
        int perm = context.checkCallingOrSelfPermission("android.permission." + permName.toString());
        return perm == PackageManager.PERMISSION_GRANTED;
    }

    private String getLocationAddress(Context mContext, Location location) {
        String addNow = "";
        Geocoder geoCoder = new Geocoder(mContext, Locale.CHINESE);
        try {
            List<Address> addresses = geoCoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
            Address address = addresses.get(0);
            LogcatUtils.e("LocationTool", "远程获取定位全部为: " + address.toString());

            if (address.getAddressLine(0) != null && !address.getAddressLine(0).equals("")) {
                addNow = address.getAddressLine(0);
                LogcatUtils.e("LocationTool", "获取成功第一种: " + addNow);
            } else if (addNow.equals("") && address.getFeatureName() != null && !address.getFeatureName().equals("")) {
                addNow = address.getLocality() + address.getFeatureName();
                LogcatUtils.e("LocationTool", "获取成功第二种: " + addNow);
            } else {
                int maxLine = address.getMaxAddressLineIndex();
                if (maxLine >= 2) {
                    addNow = address.getAddressLine(1) + address.getAddressLine(2);
                } else {
                    addNow = address.getAddressLine(1);
                }
                LogcatUtils.e("LocationTool", "获取成功第三种: " + addNow);
            }

        } catch (IOException e) {
            addNow = "";
            e.printStackTrace();
        }
        if (addNow.contains("null")) {
            addNow = addNow.replaceAll("null", "");
        }
        return addNow;
    }

    /**
     * 根据 纬度 精度 获取位置
     *
     * @param context
     * @param latitude  纬度
     * @param longitude 精度
     * @return
     */
    public String getLocationAddress(Context context, double latitude, double longitude) {
        String addNow = "";
        Geocoder geoCoder = new Geocoder(context, Locale.CHINESE);
        try {
            List<Address> addresses = geoCoder.getFromLocation(latitude, longitude, 1);
            if (addresses.size() > 0) {
                Address address = addresses.get(0);
                LogcatUtils.e("LocationTool", "远程获取定位全部为: " + address.toString());

                if (address.getAddressLine(0) != null && !address.getAddressLine(0).equals("")) {
                    addNow = address.getAddressLine(0);
                    LogcatUtils.e("LocationTool", "获取成功第一种: " + addNow + " code " + address.getCountryCode());
                } else if (addNow.equals("") && address.getFeatureName() != null && !address.getFeatureName().equals("")) {
                    addNow = address.getLocality() + address.getFeatureName();
                    LogcatUtils.e("LocationTool", "获取成功第二种: " + addNow + " code " + address.getCountryCode());
                } else {
                    int maxLine = address.getMaxAddressLineIndex();
                    if (maxLine >= 2) {
                        addNow = address.getAddressLine(1) + address.getAddressLine(2);
                    } else {
                        addNow = address.getAddressLine(1);
                    }
                    LogcatUtils.e("LocationTool", "获取成功第三种: " + addNow + " code " + address.getCountryCode());
                }
            }

        } catch (IOException e) {
            addNow = "";
            e.printStackTrace();
        }
        if (addNow.contains("null")) {
            addNow = addNow.replaceAll("null", "");
        }
        return addNow;
    }

    public String getLocationCountryCode(Context context, double latitude, double longitude) {
        String addNow = "";
        Geocoder geoCoder = new Geocoder(context, Locale.CHINESE);
        try {
            List<Address> addresses = geoCoder.getFromLocation(latitude, longitude, 1);
            if (addresses.size() > 0) {
                Address address = addresses.get(0);
                LogcatUtils.e("LocationTool", "远程获取定位全部为: " + address.toString());

                addNow = address.getCountryCode();
            }

        } catch (IOException e) {
            addNow = "";
            e.printStackTrace();
        }
        if (addNow.contains("null")) {
            addNow = addNow.replaceAll("null", "");
        }
        return addNow;
    }

    /**
     * 判断GPS是否开启，GPS或者AGPS开启一个就认为是开启的
     *
     * @param context
     * @return true 表示开启
     */
    private boolean isOPenGPS(final Context context) {
        LocationManager locationManager
                = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        // GPS定位
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        // 网络服务定位
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (gps || network) {
            return true;
        }
        return false;
    }

    private enum permission {
        ACCESS_COARSE_LOCATION,
        ACCESS_FINE_LOCATION
    }

}
